home *** CD-ROM | disk | FTP | other *** search
/ IRIX Base Documentation 2001 May / SGI IRIX Base Documentation 2001 May.iso / usr / share / catman / u_man / cat1 / perlsec.z / perlsec
Encoding:
Text File  |  1998-10-30  |  20.9 KB  |  463 lines

  1.  
  2.  
  3.  
  4. PPPPEEEERRRRLLLLSSSSEEEECCCC((((1111))))                                                          PPPPEEEERRRRLLLLSSSSEEEECCCC((((1111))))
  5.  
  6.  
  7.  
  8. NNNNAAAAMMMMEEEE
  9.      perlsec - Perl security
  10.  
  11. DDDDEEEESSSSCCCCRRRRIIIIPPPPTTTTIIIIOOOONNNN
  12.      Perl is designed to make it easy to program securely even when running
  13.      with extra privileges, like setuid or setgid programs.  Unlike most
  14.      command line shells, which are based on multiple substitution passes on
  15.      each line of the script, Perl uses a more conventional evaluation scheme
  16.      with fewer hidden snags.  Additionally, because the language has more
  17.      builtin functionality, it can rely less upon external (and possibly
  18.      untrustworthy) programs to accomplish its purposes.
  19.  
  20.      Perl automatically enables a set of special security checks, called _t_a_i_n_t
  21.      _m_o_d_e, when it detects its program running with differing real and
  22.      effective user or group IDs.  The setuid bit in Unix permissions is mode
  23.      04000, the setgid bit mode 02000; either or both may be set.  You can
  24.      also enable taint mode explicitly by using the ----TTTT command line flag. This
  25.      flag is _s_t_r_o_n_g_l_y suggested for server programs and any program run on
  26.      behalf of someone else, such as a CGI script. Once taint mode is on, it's
  27.      on for the remainder of your script.
  28.  
  29.      While in this mode, Perl takes special precautions called _t_a_i_n_t _c_h_e_c_k_s to
  30.      prevent both obvious and subtle traps.  Some of these checks are
  31.      reasonably simple, such as verifying that path directories aren't
  32.      writable by others; careful programmers have always used checks like
  33.      these.  Other checks, however, are best supported by the language itself,
  34.      and it is these checks especially that contribute to making a set-id Perl
  35.      program more secure than the corresponding C program.
  36.  
  37.      You may not use data derived from outside your program to affect
  38.      something else outside your program--at least, not by accident.  All
  39.      command line arguments, environment variables, locale information (see
  40.      the _p_e_r_l_l_o_c_a_l_e manpage), results of certain system calls (readdir,
  41.      readlink, the gecos field of getpw* calls), and all file input are marked
  42.      as "tainted".  Tainted data may not be used directly or indirectly in any
  43.      command that invokes a sub-shell, nor in any command that modifies files,
  44.      directories, or processes.  Any variable set to a value derived from
  45.      tainted data will itself be tainted, even if it is logically impossible
  46.      for the tainted data to alter the variable.  Because taintedness is
  47.      associated with each scalar value, some elements of an array can be
  48.      tainted and others not.
  49.  
  50.      For example:
  51.  
  52.          $arg = shift;               # $arg is tainted
  53.          $hid = $arg, 'bar';         # $hid is also tainted
  54.          $line = <>;                 # Tainted
  55.          $line = <STDIN>;            # Also tainted
  56.          open FOO, "/home/me/bar" or die $!;
  57.          $line = <FOO>;              # Still tainted
  58.          $path = $ENV{'PATH'};       # Tainted, but see below
  59.          $data = 'abc';              # Not tainted
  60.  
  61.  
  62.  
  63.                                                                         PPPPaaaaggggeeee 1111
  64.  
  65.  
  66.  
  67.  
  68.  
  69.  
  70. PPPPEEEERRRRLLLLSSSSEEEECCCC((((1111))))                                                          PPPPEEEERRRRLLLLSSSSEEEECCCC((((1111))))
  71.  
  72.  
  73.  
  74.          system "echo $arg";         # Insecure
  75.          system "/bin/echo", $arg;   # Secure (doesn't use sh)
  76.          system "echo $hid";         # Insecure
  77.          system "echo $data";        # Insecure until PATH set
  78.  
  79.          $path = $ENV{'PATH'};       # $path now tainted
  80.  
  81.          $ENV{'PATH'} = '/bin:/usr/bin';
  82.          delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};
  83.  
  84.          $path = $ENV{'PATH'};       # $path now NOT tainted
  85.          system "echo $data";        # Is secure now!
  86.  
  87.          open(FOO, "< $arg");        # OK - read-only file
  88.          open(FOO, "> $arg");        # Not OK - trying to write
  89.  
  90.          open(FOO,"echo $arg|");     # Not OK, but...
  91.          open(FOO,"-|")
  92.              or exec 'echo', $arg;   # OK
  93.  
  94.          $shout = `echo $arg`;       # Insecure, $shout now tainted
  95.  
  96.          unlink $data, $arg;         # Insecure
  97.          umask $arg;                 # Insecure
  98.  
  99.          exec "echo $arg";           # Insecure
  100.          exec "echo", $arg;          # Secure (doesn't use the shell)
  101.          exec "sh", '-c', $arg;      # Considered secure, alas!
  102.  
  103.          @files = <*.c>;             # Always insecure (uses csh)
  104.          @files = glob('*.c');       # Always insecure (uses csh)
  105.  
  106.      If you try to do something insecure, you will get a fatal error saying
  107.      something like "Insecure dependency" or "Insecure PATH".  Note that you
  108.      can still write an insecure ssssyyyysssstttteeeemmmm or eeeexxxxeeeecccc, but only by explicitly doing
  109.      something like the last example above.
  110.  
  111.      LLLLaaaauuuunnnnddddeeeerrrriiiinnnngggg aaaannnndddd DDDDeeeetttteeeeccccttttiiiinnnngggg TTTTaaaaiiiinnnntttteeeedddd DDDDaaaattttaaaa
  112.  
  113.      To test whether a variable contains tainted data, and whose use would
  114.      thus trigger an "Insecure dependency" message, check your nearby CPAN
  115.      mirror for the _T_a_i_n_t._p_m module, which should become available around
  116.      November 1997.  Or you may be able to use the following _i_s__t_a_i_n_t_e_d()
  117.      function.
  118.  
  119.          sub is_tainted {
  120.              return ! eval {
  121.                  join('',@_), kill 0;
  122.                  1;
  123.              };
  124.          }
  125.  
  126.  
  127.  
  128.  
  129.                                                                         PPPPaaaaggggeeee 2222
  130.  
  131.  
  132.  
  133.  
  134.  
  135.  
  136. PPPPEEEERRRRLLLLSSSSEEEECCCC((((1111))))                                                          PPPPEEEERRRRLLLLSSSSEEEECCCC((((1111))))
  137.  
  138.  
  139.  
  140.      This function makes use of the fact that the presence of tainted data
  141.      anywhere within an expression renders the entire expression tainted.  It
  142.      would be inefficient for every operator to test every argument for
  143.      taintedness.  Instead, the slightly more efficient and conservative
  144.      approach is used that if any tainted value has been accessed within the
  145.      same expression, the whole expression is considered tainted.
  146.  
  147.      But testing for taintedness gets you only so far.  Sometimes you have
  148.      just to clear your data's taintedness.  The only way to bypass the
  149.      tainting mechanism is by referencing subpatterns from a regular
  150.      expression match.  Perl presumes that if you reference a substring using
  151.      $1, $2, etc., that you knew what you were doing when you wrote the
  152.      pattern.  That means using a bit of thought--don't just blindly untaint
  153.      anything, or you defeat the entire mechanism.  It's better to verify that
  154.      the variable has only good characters (for certain values of "good")
  155.      rather than checking whether it has any bad characters.  That's because
  156.      it's far too easy to miss bad characters that you never thought of.
  157.  
  158.      Here's a test to make sure that the data contains nothing but "word"
  159.      characters (alphabetics, numerics, and underscores), a hyphen, an at
  160.      sign, or a dot.
  161.  
  162.          if ($data =~ /^([-\@\w.]+)$/) {
  163.              $data = $1;                     # $data now untainted
  164.          } else {
  165.              die "Bad data in $data";        # log this somewhere
  166.          }
  167.  
  168.      This is fairly secure because /\w+/ doesn't normally match shell
  169.      metacharacters, nor are dot, dash, or at going to mean something special
  170.      to the shell.  Use of /.+/ would have been insecure in theory because it
  171.      lets everything through, but Perl doesn't check for that.  The lesson is
  172.      that when untainting, you must be exceedingly careful with your patterns.
  173.      Laundering data using regular expression is the _O_N_L_Y mechanism for
  174.      untainting dirty data, unless you use the strategy detailed below to fork
  175.      a child of lesser privilege.
  176.  
  177.      The example does not untaint $data if use locale is in effect, because
  178.      the characters matched by \w are determined by the locale.  Perl
  179.      considers that locale definitions are untrustworthy because they contain
  180.      data from outside the program.  If you are writing a locale-aware
  181.      program, and want to launder data with a regular expression containing
  182.      \w, put no locale ahead of the expression in the same block.  See the
  183.      SECURITY entry in the _p_e_r_l_l_o_c_a_l_e manpage for further discussion and
  184.      examples.
  185.  
  186.      SSSSwwwwiiiittttcccchhhheeeessss OOOOnnnn tttthhhheeee """"####!!!!"""" LLLLiiiinnnneeee
  187.  
  188.      When you make a script executable, in order to make it usable as a
  189.      command, the system will pass switches to perl from the script's #!
  190.      line.  Perl checks that any command line switches given to a setuid (or
  191.      setgid) script actually match the ones set on the #! line.  Some Unix and
  192.  
  193.  
  194.  
  195.                                                                         PPPPaaaaggggeeee 3333
  196.  
  197.  
  198.  
  199.  
  200.  
  201.  
  202. PPPPEEEERRRRLLLLSSSSEEEECCCC((((1111))))                                                          PPPPEEEERRRRLLLLSSSSEEEECCCC((((1111))))
  203.  
  204.  
  205.  
  206.      Unix-like environments impose a one-switch limit on the #!  line, so you
  207.      may need to use something like -wU instead of -w -U under such systems.
  208.      (This issue should arise only in Unix or Unix-like environments that
  209.      support #! and setuid or setgid scripts.)
  210.  
  211.      CCCClllleeeeaaaannnniiiinnnngggg UUUUpppp YYYYoooouuuurrrr PPPPaaaatttthhhh
  212.  
  213.      For "Insecure $ENV{PATH}" messages, you need to set $ENV{'PATH'} to a
  214.      known value, and each directory in the path must be non-writable by
  215.      others than its owner and group.  You may be surprised to get this
  216.      message even if the pathname to your executable is fully qualified.  This
  217.      is _n_o_t generated because you didn't supply a full path to the program;
  218.      instead, it's generated because you never set your PATH environment
  219.      variable, or you didn't set it to something that was safe.  Because Perl
  220.      can't guarantee that the executable in question isn't itself going to
  221.      turn around and execute some other program that is dependent on your
  222.      PATH, it makes sure you set the PATH.
  223.  
  224.      It's also possible to get into trouble with other operations that don't
  225.      care whether they use tainted values.  Make judicious use of the file
  226.      tests in dealing with any user-supplied filenames.  When possible, do
  227.      opens and such aaaafffftttteeeerrrr properly dropping any special user (or group!)
  228.      privileges. Perl doesn't prevent you from opening tainted filenames for
  229.      reading, so be careful what you print out.  The tainting mechanism is
  230.      intended to prevent stupid mistakes, not to remove the need for thought.
  231.  
  232.      Perl does not call the shell to expand wild cards when you pass ssssyyyysssstttteeeemmmm
  233.      and eeeexxxxeeeecccc explicit parameter lists instead of strings with possible shell
  234.      wildcards in them.  Unfortunately, the ooooppppeeeennnn, gggglllloooobbbb, and backtick functions
  235.      provide no such alternate calling convention, so more subterfuge will be
  236.      required.
  237.  
  238.      Perl provides a reasonably safe way to open a file or pipe from a setuid
  239.      or setgid program: just create a child process with reduced privilege who
  240.      does the dirty work for you.  First, fork a child using the special ooooppppeeeennnn
  241.      syntax that connects the parent and child by a pipe.  Now the child
  242.      resets its ID set and any other per-process attributes, like environment
  243.      variables, umasks, current working directories, back to the originals or
  244.      known safe values.  Then the child process, which no longer has any
  245.      special permissions, does the ooooppppeeeennnn or other system call.  Finally, the
  246.      child passes the data it managed to access back to the parent.  Because
  247.      the file or pipe was opened in the child while running under less
  248.      privilege than the parent, it's not apt to be tricked into doing
  249.      something it shouldn't.
  250.  
  251.      Here's a way to do backticks reasonably safely.  Notice how the eeeexxxxeeeecccc is
  252.      not called with a string that the shell could expand.  This is by far the
  253.      best way to call something that might be subjected to shell escapes: just
  254.      never call the shell at all.
  255.  
  256.  
  257.  
  258.  
  259.  
  260.  
  261.                                                                         PPPPaaaaggggeeee 4444
  262.  
  263.  
  264.  
  265.  
  266.  
  267.  
  268. PPPPEEEERRRRLLLLSSSSEEEECCCC((((1111))))                                                          PPPPEEEERRRRLLLLSSSSEEEECCCC((((1111))))
  269.  
  270.  
  271.  
  272.          use English;
  273.          die "Can't fork: $!" unless defined $pid = open(KID, "-|");
  274.          if ($pid) {           # parent
  275.              while (<KID>) {
  276.                  # do something
  277.              }
  278.              close KID;
  279.          } else {
  280.              my @temp = ($EUID, $EGID);
  281.              $EUID = $UID;
  282.              $EGID = $GID;    # XXX: initgroups() not called
  283.              # Make sure privs are really gone
  284.              ($EUID, $EGID) = @temp;
  285.              die "Can't drop privileges" unless
  286.                  $UID == $EUID and
  287.                  $GID eq $EGID;      # String test
  288.              $ENV{PATH} = "/bin:/usr/bin";
  289.              exec 'myprog', 'arg1', 'arg2' or
  290.              die "can't exec myprog: $!";
  291.          }
  292.  
  293.      A similar strategy would work for wildcard expansion via glob, although
  294.      you can use readdir instead.
  295.  
  296.      Taint checking is most useful when although you trust yourself not to
  297.      have written a program to give away the farm, you don't necessarily trust
  298.      those who end up using it not to try to trick it into doing something
  299.      bad.  This is the kind of security checking that's useful for set-id
  300.      programs and programs launched on someone else's behalf, like CGI
  301.      programs.
  302.  
  303.      This is quite different, however, from not even trusting the writer of
  304.      the code not to try to do something evil.  That's the kind of trust
  305.      needed when someone hands you a program you've never seen before and
  306.      says, "Here, run this."  For that kind of safety, check out the Safe
  307.      module, included standard in the Perl distribution.  This module allows
  308.      the programmer to set up special compartments in which all system
  309.      operations are trapped and namespace access is carefully controlled.
  310.  
  311.      SSSSeeeeccccuuuurrrriiiittttyyyy BBBBuuuuggggssss
  312.  
  313.      Beyond the obvious problems that stem from giving special privileges to
  314.      systems as flexible as scripts, on many versions of Unix, set-id scripts
  315.      are inherently insecure right from the start.  The problem is a race
  316.      condition in the kernel.  Between the time the kernel opens the file to
  317.      see which interpreter to run and when the (now-set-id) interpreter turns
  318.      around and reopens the file to interpret it, the file in question may
  319.      have changed, especially if you have symbolic links on your system.
  320.  
  321.      Fortunately, sometimes this kernel "feature" can be disabled.
  322.      Unfortunately, there are two ways to disable it.  The system can simply
  323.      outlaw scripts with any set-id bit set, which doesn't help much.
  324.  
  325.  
  326.  
  327.                                                                         PPPPaaaaggggeeee 5555
  328.  
  329.  
  330.  
  331.  
  332.  
  333.  
  334. PPPPEEEERRRRLLLLSSSSEEEECCCC((((1111))))                                                          PPPPEEEERRRRLLLLSSSSEEEECCCC((((1111))))
  335.  
  336.  
  337.  
  338.      Alternately, it can simply ignore the set-id bits on scripts.  If the
  339.      latter is true, Perl can emulate the setuid and setgid mechanism when it
  340.      notices the otherwise useless setuid/gid bits on Perl scripts.  It does
  341.      this via a special executable called ssssuuuuiiiiddddppppeeeerrrrllll that is automatically
  342.      invoked for you if it's needed.
  343.  
  344.      However, if the kernel set-id script feature isn't disabled, Perl will
  345.      complain loudly that your set-id script is insecure.  You'll need to
  346.      either disable the kernel set-id script feature, or put a C wrapper
  347.      around the script.  A C wrapper is just a compiled program that does
  348.      nothing except call your Perl program.   Compiled programs are not
  349.      subject to the kernel bug that plagues set-id scripts.  Here's a simple
  350.      wrapper, written in C:
  351.  
  352.          #define REAL_PATH "/path/to/script"
  353.          main(ac, av)
  354.              char **av;
  355.          {
  356.              execv(REAL_PATH, av);
  357.          }
  358.  
  359.      Compile this wrapper into a binary executable and then make _i_t rather
  360.      than your script setuid or setgid.
  361.  
  362.      See the program wwwwrrrraaaappppssssuuuuiiiidddd in the _e_g directory of your Perl distribution
  363.      for a convenient way to do this automatically for all your setuid Perl
  364.      programs.  It moves setuid scripts into files with the same name plus a
  365.      leading dot, and then compiles a wrapper like the one above for each of
  366.      them.
  367.  
  368.      In recent years, vendors have begun to supply systems free of this
  369.      inherent security bug.  On such systems, when the kernel passes the name
  370.      of the set-id script to open to the interpreter, rather than using a
  371.      pathname subject to meddling, it instead passes /_d_e_v/_f_d/_3.  This is a
  372.      special file already opened on the script, so that there can be no race
  373.      condition for evil scripts to exploit.  On these systems, Perl should be
  374.      compiled with -DSETUID_SCRIPTS_ARE_SECURE_NOW.  The CCCCoooonnnnffffiiiigggguuuurrrreeee program
  375.      that builds Perl tries to figure this out for itself, so you should never
  376.      have to specify this yourself.  Most modern releases of SysVr4 and BSD
  377.      4.4 use this approach to avoid the kernel race condition.
  378.  
  379.      Prior to release 5.003 of Perl, a bug in the code of ssssuuuuiiiiddddppppeeeerrrrllll could
  380.      introduce a security hole in systems compiled with strict POSIX
  381.      compliance.
  382.  
  383.      PPPPrrrrooootttteeeeccccttttiiiinnnngggg YYYYoooouuuurrrr PPPPrrrrooooggggrrrraaaammmmssss
  384.  
  385.      There are a number of ways to hide the source to your Perl programs, with
  386.      varying levels of "security".
  387.  
  388.  
  389.  
  390.  
  391.  
  392.  
  393.                                                                         PPPPaaaaggggeeee 6666
  394.  
  395.  
  396.  
  397.  
  398.  
  399.  
  400. PPPPEEEERRRRLLLLSSSSEEEECCCC((((1111))))                                                          PPPPEEEERRRRLLLLSSSSEEEECCCC((((1111))))
  401.  
  402.  
  403.  
  404.      First of all, however, you _c_a_n'_t take away read permission, because the
  405.      source code has to be readable in order to be compiled and interpreted.
  406.      (That doesn't mean that a CGI script's source is readable by people on
  407.      the web, though.)  So you have to leave the permissions at the socially
  408.      friendly 0755 level.
  409.  
  410.      Some people regard this as a security problem.  If your program does
  411.      insecure things, and relies on people not knowing how to exploit those
  412.      insecurities, it is not secure.  It is often possible for someone to
  413.      determine the insecure things and exploit them without viewing the
  414.      source.  Security through obscurity, the name for hiding your bugs
  415.      instead of fixing them, is little security indeed.
  416.  
  417.      You can try using encryption via source filters (Filter::* from CPAN).
  418.      But crackers might be able to decrypt it.  You can try using the byte
  419.      code compiler and interpreter described below, but crackers might be able
  420.      to de-compile it.  You can try using the native-code compiler described
  421.      below, but crackers might be able to disassemble it.  These pose varying
  422.      degrees of difficulty to people wanting to get at your code, but none can
  423.      definitively conceal it (this is true of every language, not just Perl).
  424.  
  425.      If you're concerned about people profiting from your code, then the
  426.      bottom line is that nothing but a restrictive licence will give you legal
  427.      security.  License your software and pepper it with threatening
  428.      statements like "This is unpublished proprietary software of XYZ Corp.
  429.      Your access to it does not give you permission to use it blah blah blah."
  430.      You should see a lawyer to be sure your licence's wording will stand up
  431.      in court.
  432.  
  433.  
  434.  
  435.  
  436.  
  437.  
  438.  
  439.  
  440.  
  441.  
  442.  
  443.  
  444.  
  445.  
  446.  
  447.  
  448.  
  449.  
  450.  
  451.  
  452.  
  453.  
  454.  
  455.  
  456.  
  457.  
  458.  
  459.                                                                         PPPPaaaaggggeeee 7777
  460.  
  461.  
  462.  
  463.